#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009 Iván G. Campaña N. (e-van) <ivan.campana at gmail.com>
# Released under GNU General Public License

import urllib2
import urlparse
import re

try:
  from hashlib import md5
except ImportError:
  from md5 import md5
  
import os.path

currentUrl = None

def is_relative_to_server(url):
    parts = urlparse.urlparse(url)
    if parts[0] or parts[1]:
        return 0
    return 1

def open_url(url):
	
	# finds if the url is a local file, that way it skips some operations and responds faster
	# specially with cached avatar images.
	
	if url[0:4] == "file":
		my_file =  open(url[7:], "r")
		return my_file
	
	uri = resolve_uri(url)
	return urllib2.urlopen(url, timeout = 60)

def resolve_uri(uri):
    if is_relative_to_server(uri):
        return urlparse.urljoin(currentUrl, uri)
    return uri

def request_url(document, url, stream):
	f = open_url(url)
	content = f.read()
	
	stream.write(content)
	
	#Really important, always close the stream specially for images
	stream.close()
	
search_nick = re.compile("@([A-Za-z_0-9]*)", re.MULTILINE | re.DOTALL)
search_hashtag = re.compile("#([A-Za-z_\-0-9]*)", re.MULTILINE | re.DOTALL)
search_url = re.compile("http://([A-Za-z_0-9\./#?&=+\-]*)", re.MULTILINE | re.DOTALL)

def find_url(text):
	"Tries to find any URL in the text and create a corresponding link"
	
	new_text = text
	matches = search_url.findall(text)
	
	if matches:
		for url in matches:
			new_url = "http://%s" % url
			#new_text = new_text.replace(new_url, '<a href="%(url)s">%(url)s</a>' % {'url': new_url})
			new_text = new_text.replace(new_url, '<span foreground="#0000FF"><u>%(url)s</u></span>' % {'url': new_url})
			
	return new_text
	
def find_nick(text):
	"Tries to find all the ocurrences of a nick in a piece of text and link it"
	
	new_text = text
	matches = search_nick.findall(text)
	if matches:
		## Removes the duplicate matches from list, causes problems with string replacement
		new_matches = dict.fromkeys(matches).keys()

		for nick in new_matches:
			new_nick = "@%s" % nick
			if new_nick == "@":
				continue
			#new_text = new_text.replace(new_nick, '<a href="nick:%(nick)s" class="nicks">%(nick)s</a>' % {'nick' : new_nick} )
			new_text = new_text.replace(new_nick, '<span foreground="#FF0000"><u>%(nick)s</u></span>' % {'nick' : new_nick} )
			
	return new_text

def cache_image(image_url, path, url_format = True):
	url_hash = md5(image_url).hexdigest()
	
	extension = image_url.split(".")[-1]
	
	file_hash = "%s/%s.%s" % (path, url_hash, extension)
	
	if not os.path.exists(file_hash):
		f = open_url(image_url)
		fImage = open(file_hash, "wb")
		fImage.write(f.read())
		fImage.close()
	
	if url_format:
	  file_hash = "file://%s" % file_hash
	
	return file_hash

def find_hashtag(text):
	"Tries to find all the ocurrences of a hashtag in a piece of text and link it"
	
	new_text = text
	matches = search_hashtag.findall(text)
	if matches:
		new_matches = dict.fromkeys(matches).keys()

		for hash in new_matches:
			new_hash = "#%s" % hash
			if new_hash == "#":
				continue
			#new_text = new_text.replace(new_hash, '<a href="hash:%(hash)s" class="hashtags">%(hash)s</a>' % {'hash': new_hash })
			new_text = new_text.replace(new_hash, '<u>%(hash)s</u>' % {'hash': new_hash })
			
	return new_text

def find_elements(text):
	return find_url( find_nick( find_hashtag (text)))
